package com.lzp.java.concurrent.atomic;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 高并发场景下，LongAdder性能优于AtomicLong
 *
 * @author lzp
 * @date 2020/04/25
 */
public class AtomicLongConsumeTime {
    public static void main(String[] args) {
        AtomicLong counter = new AtomicLong(0);
        ExecutorService pool = new ThreadPoolExecutor(20, 20, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            pool.execute(new Task(counter));
        }
        // 关闭线程池，自旋检测线程池状态
        pool.shutdown();
        while (!pool.isTerminated()) {
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
        System.out.println(counter.get());

    }

    static class Task implements Runnable {
        private AtomicLong counter;

        public Task(AtomicLong counter) {
            this.counter = counter;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                counter.incrementAndGet();
            }
        }
    }
}
